<?php
namespace App\Api\Controllers;
use Common\ApiController;
use Common\Common;
use Common\Models\BShopAddress;
use Common\Models\BShopCityRegion;
use Common\Models\BShopGoods;
use Common\Models\BShopGoodsCategory;
use Common\Models\BShopGoodsComment;
use Common\Models\BShopGoodsSku;
use Common\Models\BShopOrder;
use Common\Models\BShopOrderAddress;
use Common\Models\BShopOrderCount;
use Common\Models\BShopOrderRefund;
use Common\Models\BShopRefundReasion;
use Common\Models\BShopUsers;
use Common\Models\BshopUsersInfo;
use Common\Models\FWalletsAmountLog;
use Common\Models\FWalletsShopAmountLog;
use Common\Models\FWalletsShopFreezeAmountLog;
use Common\Models\Wallets;
use Common\ShopModels\BShopMessageSysmess;
use Library\Tools\RedisTools;
use Services\Api\ShopOrderServices;

class ShopController extends ApiController
{
    public function initialize()
    {
        parent::initialize();
    }


    public function shop_applyAction(){
        if(!isset($this->params['shop_name']) || empty($this->params['shop_name'])){
            $this->fail(-1,'名称不能为空');
        }
        if(!isset($this->params['shop_avatar']) || empty($this->params['shop_avatar'])){
            $this->fail(-1,'LOGO不能为空');
        }
        if(!isset($this->params['shop_real_name']) || empty($this->params['shop_real_name'])){
            $this->fail(-1,'店主真实姓名不能为空');
        }
        if(!isset($this->params['category_id']) || empty($this->params['category_id'])){
            $this->fail(-1,'请选择分类');
        }
        if(!isset($this->params['shop_address']) || empty($this->params['shop_address'])){
            $this->fail(-1,'店铺地址不能为空');
        }
        if(!isset($this->params['id_card']) || empty($this->params['id_card'])){
            $this->fail(-1,'请输入你的身份证编号');
        }
        if(!isset($this->params['business_license']) || empty($this->params['business_license'])){
            $this->fail(-1,'请上传营业执照');
        }
        if(!isset($this->params['id_card_img_z']) || empty($this->params['id_card_img_z'])){
            $this->fail(-1,'请上传身份证正面图');
        }
        if(!isset($this->params['id_card_img_f']) || empty($this->params['id_card_img_f'])){
            $this->fail(-1,'请上传身份证反面图');
        }
        $this->params['id_card_img'] = "{$this->params['id_card_img_z']},{$this->params['id_card_img_f']}";

        if(!isset($this->params['address_area_code'])|| empty($this->params['address_area_code'])){
            $this->fail(-1,'请选择地区');
        }else{
            $BshopCityRegionDb = new BShopCityRegion();
            $region_city = $BshopCityRegionDb->find(array(
                "conditions"=>"id in({$this->params['address_area_code']})",
                "columns"=>"id,name",
            ))->toarray();
            if($region_city){
                $shop_address = implode(",",array_column($region_city,'name'));
                $this->params['shop_address'] = $shop_address.",{$this->params['shop_address']}";
            }
        }

        $key        = 'd35ccb7840367a7ace5062d0566f15c7';
        $url        = "https://restapi.amap.com/v3/geocode/geo?key={$key}&address={$this->params['shop_address']}";
        $res        = json_decode(file_get_contents($url), true);
        $latitude_longitude = '';
        if(isset($res['status']) && $res['status']==1) {
            if (isset($res['geocodes'][0]['location'])) {
                $latitude_longitude = $res['geocodes'][0]['location'];
            }
        }
        $this->params['latitude_longitude'] = $latitude_longitude;

        $this->dbMaster->begin();
        $BShopUserDb = new BShopUsers();
        $shop_user_info = $BShopUserDb->findFirstByUserId($this->user_info['id']);
        if($shop_user_info){
            if(in_array($shop_user_info->status,[1,2])){
                $this->fail(-1,'您已经申请了店铺了');
            }
        }else{
            $shop_user_info = new BShopUsers();
        }
        $shop_user_info->name=$this->user_info['phone'];
        $shop_user_info->password=md5($this->user_info['phone']);
        $shop_user_info->username=$this->params['shop_name'];
        $shop_user_info->status = 3;
        $shop_user_info->role_group=1;
        $shop_user_info->created_at = date('Y-m-d H:i:s');
        $shop_user_info->updated_at = date('Y-m-d H:i:s');
        $shop_user_info->introduction = '店主身份已经提交';
        $shop_user_info->avatar = $this->params['shop_avatar'];
        $shop_user_info->user_id = $this->user_info['id'];
        $shop_user_info->introduction = $this->params['shop_introduction'];
        if(!$shop_user_info->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'后台账号提交出错！');
        }

        $BShopUserInfoDB = new BshopUsersInfo();
        $b_shop_user_info = $BShopUserInfoDB->findFirstByShopId($shop_user_info->id);
        if(!$b_shop_user_info){
            $b_shop_user_info = new BshopUsersInfo();
        }
        $b_shop_user_info->shop_name = $this->params['shop_name'];
        $b_shop_user_info->shop_id = $shop_user_info->id;
        $b_shop_user_info->category_id = $shop_user_info->category_id;
        $b_shop_user_info->shop_address = $shop_user_info->shop_address;
        $b_shop_user_info->shop_avatar = $this->params['shop_avatar'];
        $b_shop_user_info->shop_real_name = $this->params['shop_real_name'];
        $b_shop_user_info->id_card = $this->params['id_card'];
        $b_shop_user_info->business_license = $this->params['business_license'];
        $b_shop_user_info->is_disable = 3;
        $b_shop_user_info->shop_real_name = $this->params['shop_real_name'];
        $b_shop_user_info->created_at = date('Y-m-d H:i:s');
        $b_shop_user_info->id_card_img = $this->params['id_card_img'];
        $b_shop_user_info->shop_introduction = $this->params['shop_introduction'];
        $b_shop_user_info->address_area_code = $this->params['address_area_code'];
        if(!$b_shop_user_info->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'店主身份提交出错');
        }
        $this->dbMaster->commit();
        $this->ok([]);
    }


    /**
     * 店铺街
     */
    public function shop_streetAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page']=1;
        }
        if(!isset($this->params['page_size']) || empty($this->params['page_size'])){
            $this->params['page_size']=10;
        }
        $BShopUserInfoDb = new BshopUsersInfo();
        $get_list = $BShopUserInfoDb->get_shop_goods_list($this->params);
        $BShopGoodsDb = new BShopGoods();
        foreach($get_list as $key=>$value){
            $get_list[$key]['child'] = $this->money_less($BShopGoodsDb->get_goods_list($value['shop_id']));
        }
        $this->ok($get_list);
    }



    public function related_suggestAction(){
        if(!isset($this->params['goods_id']) || empty($this->params['goods_id'])){
            $this->fail(-1,'商品id不能为空');
        }
        $BShopGoodsDB = new BShopGoods();
        $b_shop_goods = $BShopGoodsDB->findFirstByGoodsSn($this->params['goods_id']);
        if(!$b_shop_goods){
            $this->fail(-1,'没有找到商品');
        }
        $params['category_id'] = $b_shop_goods->category_id;
        $params['page'] =  1;
        $params['page_size'] = 10;
        $get_list = $BShopGoodsDB->get_goods_index();
        $this->ok($get_list);

    }


    /**
     * 店铺详细信息
     */
    public function shop_infoAction(){
        if(!isset($this->params['shop_id']) || empty($this->params['shop_id'])){
            $this->fail(-1,'id不能为空');
        }
        $BShopUserInfoDb = new BshopUsersInfo();
        $shop_info = $BShopUserInfoDb->find_first($this->params['shop_id']);
        if(!$shop_info){
            $this->fail(-1,'不存在，或已下架');
        }
        if($shop_info->is_disable == 0){
            $this->fail(-1,'已违规');
        }
        $this->ok($shop_info);
    }


    /**
     * 店铺商品
     */
    public function shop_goodsAction(){
        if(!isset($this->params['shop_id']) || empty($this->params['shop_id'])){
            $this->fail(-1,'id不能为空');
        }
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page']=1;
        }
        if(!isset($this->params['page_size']) || empty($this->params['page_size'])){
            $this->params['page_size']=10;
        }
        if(!isset($this->params['order_by']) || empty($this->params['order_by'])){
            $this->params['order_by']='commission';
        }
        if(!isset($this->params['sort']) || empty($this->params['sort'])){
            $this->params['sort']='DESC';
        }
        $BShopUserInfoDb = new BshopUsersInfo();
        $shop_info = $BShopUserInfoDb->find_first($this->params['shop_id']);
        if(!$shop_info){
            $this->fail(-1,'不存在，或已下架');
        }
        if($shop_info->is_disable == 0){
            $this->fail(-1,'已违规');
        }
        $BShopGoodsDb = new BShopGoods();
        $get_list = $BShopGoodsDb->shop_goods_list($this->params);
        $get_list = $this->money_less($get_list);
        $this->ok($get_list);
    }


    /**
     * 获取全部省市区
     */
    public function city_regionAction(){
        $BShopCityRegionDb = new BShopCityRegion();
        $new_city=[];
        $bshocity = $BShopCityRegionDb->find(array(
            'conditions'=>'level=1',
            'columns'=>'id as code,name'
        ))->toarray();
        foreach($bshocity as $key=>$value){
            $new_city[$key]['code']=$value['code'];
            $new_city[$key]['name']=$value['name'];
            $sheng_children = $BShopCityRegionDb->find(array(
                'conditions'=>"pid={$value['code']}",
                'columns'=>'id as code,name'
            ))->toarray();
            foreach($sheng_children as $key1=>$value1){
                $new_city[$key]['children'][$key1]['code'] = $value1['code'];
                $new_city[$key]['children'][$key1]['name'] = $value1['name'];
                $shi = $BShopCityRegionDb->find(array(
                    'conditions'=>"pid={$value1['code']}",
                    'columns'=>'id as code,name'
                ))->toarray();
                $new_city[$key]['children'][$key1]['children'] = $shi;
            }
        }
        echo json_encode($new_city);
    }


    /**
     * 获取分类
     */
    public function get_categoryAction(){
        if(!isset($this->params['pid']) || empty($this->params['pid'])){
            $this->params['pid'] = 0;
        }
        $BShopGoodsCateogryDb = new BShopGoodsCategory();
        $b_shop_goods_category = $BShopGoodsCateogryDb->goods_categories_parents($this->params['pid']);
        $this->ok($b_shop_goods_category);
    }



    //商品列表
    public function goods_listAction(){
        if(!isset($this->params['page_size']) || empty($this->params['page_size'])){
            $this->params['page_size'] = 10;
        }

        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page'] = 1;
        }
        $BShopGoodsDb = new BShopGoods();
        $goods_list = $BShopGoodsDb->get_goods_index($this->params);
        $goods_list = $this->money_less($goods_list);
        $this->ok($goods_list);
    }


    /**
     * 商品详情
     */
    public function goods_detailAction(){
        if(!isset($this->params['site']) || empty($this->params['site'])){
            $this->fail(-1,'站点不能为空');
        }
        if(!isset($this->params['goods_id']) || empty($this->params['goods_id'])){
            $this->fail(-1,'商品id不能为空');
        }
        $BShopGoodsDb = new BShopGoods();
        $goods_info[0] = $BShopGoodsDb->get_goods_sn($this->params);
        if(!$goods_info[0]){
            $this->fail(-1,'该商品已下架');
        }
        $goods_info = $this->money_less($goods_info)[0];
        $this->ok($goods_info);
    }


    /**
     * 用户下单
     */
    public function pay_orderAction(){
//        $data['price'] = 80.00;
//        $data['stock'] = 9;
//        $data['num']=1;
//        $data['sku_ids']="86_90";shop_order
//        $data['img'] = "http://qn.enshitc.com/1620462844093";
//        $data['sku_id'] = 22;
//        $data["add_jian_status"] = true;
//        $data["goods_id"] = "5_20210508164828306586898";
//        $data["goods_name"] = "这是测试商品";
//        $data["message"]="";
//        $data["pay_type"] = 1;
//        $data["all_price"] = 0.01;
//        $data["ids_arr"] = [];
//
//
//        $data1['price'] = 10.00;
//        $data1['stock'] = 9;
//        $data1['num']=1;
//        $data1['sku_ids']="86_90";
//        $data1['img'] = "http://qn.enshitc.com/1620462844093";
//        $data1['sku_id'] = 0;
//        $data1["add_jian_status"] = true;
//        $data1["goods_id"] = "5_20210508164828316586895";
//        $data1["goods_name"] = "这是测试商品cc";
//        $data1["message"]="";
//        $data1["pay_type"] = 1;
//        $data1["all_price"] = 0.01;
//        $data1["ids_arr"] = [];
//
//        $result['order_info'][0] = $data;
//        $result['order_info'][1] = $data;
//        $result['order_info'][2] = $data1;
//        $result['pay_type'] = 3;
//        $result['all_price'] = "0.03";
//        $result['address_id'] = 5;
//        $result['order_info'] = htmlspecialchars(json_encode($result['order_info']));
//        $this->params = $result;







        $redis_key="pay_order_{$this->params['user_id']}";
        $is_doing=(new RedisTools())->get($redis_key);
        if($is_doing){
            if(time() - $is_doing < 5){
                $this->fail(-1,'您提交的太频繁了');
            }
        }
        (new RedisTools())->set($redis_key,$is_doing);
        $order_info_params = json_decode(htmlspecialchars_decode($this->params['order_info']),true);
        if(!isset($order_info_params) || empty($order_info_params)){
            $this->fail(-1,'没有收到订单信息');
        }
        $result['order_info'] = $order_info_params;
        if(!isset( $this->params['address_id']) || empty( $this->params['address_id'])){
            $this->fail(-1,'请选择地址');
        }
        $result['address_id'] = $this->params['address_id'];

        if(!isset( $this->params['pay_type']) || empty( $this->params['pay_type'])){
            $this->fail(-1,'请选择支付方式');
        }
        $result['pay_type'] = $this->params['pay_type'];

        if(!isset( $this->params['all_price']) || empty( $this->params['all_price'])){
            $this->fail(-1,'请提交支付金额');
        }
        $result['all_price'] = $this->params['all_price'];

        $order_count_sn = Common::order_sn("Z");
        $pay_order_sn = Common::order_sn("P");

        $BShopGoodsDb = new BShopGoods();
        $BShopGoodsSkuDB = new BShopGoodsSku();
        $FWalletsDb = new Wallets();
        $user_wallets = $FWalletsDb->findFirstByUserId($this->user_info['id']);
        if(!$user_wallets){
            $this->fail(-1,'没有找到用户钱包');
        }

        $order_list = $result['order_info'];
        $order_all_mount=$BShopGoodsDb->all_submit_price($order_list);      //后台计算订单总金额
        if((string)$order_all_mount != (string)$result['all_price']){
            $this->fail(-1,'订单金额错误');
        }
        $pay_type = $result['pay_type'];
        if($pay_type == 3){     //判断是不是用户余额支付
            if($user_wallets->amount < $order_all_mount){
                $this->fail(-1,'钱包余额不足');
            }
        }

        $this->dbMaster->begin();
        $BshopAddressDb = new BShopAddress();
        $b_shop_order_address = $BshopAddressDb->findFirstById($result['address_id']);
        if(!$b_shop_order_address){
            $this->fail(-1,'没有找到收货地址');
        }

        $BShopOrderAddressDb = new BShopOrderAddress();
        $BShopOrderAddressDb->user_id = $this->user_info['id'];
        $BShopOrderAddressDb->name = $b_shop_order_address->name;
        $BShopOrderAddressDb->phone = $b_shop_order_address->phone;
        $BShopOrderAddressDb->address = $b_shop_order_address->province." ".$b_shop_order_address->city." ".$b_shop_order_address->area ." ".$b_shop_order_address->address;
        $BShopOrderAddressDb->created_at = date('Y-m-d H:i:s');
        $BShopOrderAddressDb->province = $b_shop_order_address->province;
        $BShopOrderAddressDb->province_code = $b_shop_order_address->province_code;
        $BShopOrderAddressDb->city = $b_shop_order_address->city;
        $BShopOrderAddressDb->city_code = $b_shop_order_address->city_code;
        $BShopOrderAddressDb->area = $b_shop_order_address->area;
        $BShopOrderAddressDb->area_code = $b_shop_order_address->area_code;
        $BShopOrderAddressDb->detail = $b_shop_order_address->address;
        if(!$BShopOrderAddressDb->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'地址写入出错');
        }

        $user_shop_freeze_amount=[];
        foreach($order_list as $key=>$value){
            $goods_info = $BShopGoodsDb->find_goods_sn($value['goods_id']);
            if(!$goods_info){
                $this->fail(-1,"商品【{$goods_info->name}】已下架");
            }
            if(isset($value['sku_id']) && !empty($value['sku_id'])){    //有规格的时候
                $find_sku = $BShopGoodsSkuDB->find_first_sku($value['sku_id']);
                if(!$find_sku){
                    $this->fail(-1,"商品【{$goods_info->name}】已经下架");
                }
                if($find_sku->stock<$value['num']){
                    $this->fail(-1,"商品【{$goods_info->name}】库存不足");
                }
                $find_sku->stock = $find_sku->stock - $value['num'];
                if(!$find_sku->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'下单出错!');
                }
            }else{//商品没有规格的时候
                if($goods_info->stock<$value['num']){
                    $this->fail(-1,"商品【{$goods_info->name}】库存不足");
                }
                $goods_info->stock = $goods_info->stock - $value['num'];
                if(!$goods_info->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'下单出错!!');
                }
            }


            $BShopOrderDb = new BShopOrder();
            $shop_order_sn =  Common::order_sn("C");
            $BShopOrderDb->type = count($order_list) > 1 ? 3 : $value['sku_id'] ? 2 : 1;
            $BShopOrderDb->order_count_sn = $order_count_sn;
            $BShopOrderDb->order_sn =$shop_order_sn;
            $BShopOrderDb->shop_id = $goods_info->shop_id;
            $BShopOrderDb->user_id = $this->user_info['id'];
            $BShopOrderDb->goods_id = $goods_info->id;
            $BShopOrderDb->goods_name = $goods_info->name;
            $BShopOrderDb->goods_sku_id = $value['sku_id'];
            $BShopOrderDb->num = $value['num'];
            $BShopOrderDb->unit_price = isset($find_sku) && !empty($find_sku) ? $find_sku->endprice : $goods_info->discount_price;
            $BShopOrderDb->end_price = $value['all_price'];
            $BShopOrderDb->address_id = $BShopOrderAddressDb->id;
            $BShopOrderDb->created_at = date('Y-m-d H:i:s');
            $BShopOrderDb->updated_at = date('Y-m-d H:i:s');
            $BShopOrderDb->status = $pay_type == 3 ? 1 : 0;
            $BShopOrderDb->settle_type = 0;
            $BShopOrderDb->pay_time = $pay_type == 3 ?  date('Y-m-d H:i:s') : null;
            $BShopOrderDb->message = $value['message'];
            $BShopOrderDb->pay_type = $pay_type;
            $BShopOrderDb->tips = "用户提交下单申请";
            $BShopOrderDb->goods_img=isset($find_sku) && !empty($find_sku) ? $find_sku->imageUrl : $goods_info->detailed_img;
            $BShopOrderDb->expired_at = date('Y-m-d H:i:s',time()+600);
            if(!$BShopOrderDb->save()){
                $this->dbMaster->rollback();
                $this->fail(-1,'下单出错!!!');
            }

            if(isset($user_shop_freeze_amount[$goods_info->shop_id])){
                $user_shop_freeze_amount[$goods_info->shop_id] = Common::bc($user_shop_freeze_amount[$goods_info->shop_id],$value['all_price'],"+",2);
            }else{
                $user_shop_freeze_amount[$goods_info->shop_id] = $value['all_price'];
            }
        }

        //店铺增加冻结余额
        if($pay_type == 3){
            $goods_name=implode('-',array_column($order_list,'goods_name'));
            foreach(array_keys($user_shop_freeze_amount) as $key=>$value) {
                $BShopUsersDb = new BShopUsers();
                $shop_user_id = $BShopUsersDb->find_shop_to_user_id($value);
                $FShopWalletsDb = new Wallets();
                $shop_wallets = $FShopWalletsDb->findFirstByUserId($shop_user_id);
                $FWalletsShopFreezeAmountLogDb = new FWalletsShopFreezeAmountLog();
                $FWalletsShopFreezeAmountLogDb->shop_id = $value;
                $FWalletsShopFreezeAmountLogDb->user_id = $this->user_info['id'];
                $FWalletsShopFreezeAmountLogDb->oil_num = $shop_wallets->shop_freeze_amount;
                $FWalletsShopFreezeAmountLogDb->this_num = Common::bc($shop_wallets->shop_freeze_amount,$user_shop_freeze_amount[$value], "+", 2);
                $FWalletsShopFreezeAmountLogDb->num = $user_shop_freeze_amount[$value];
                $FWalletsShopFreezeAmountLogDb->status = 1;
                $FWalletsShopFreezeAmountLogDb->type = 1;
                $FWalletsShopFreezeAmountLogDb->remark = "用户余额购买商品【{$goods_name}】";
                $FWalletsShopFreezeAmountLogDb->created_at = date('Y-m-d H:i:s');
                $FWalletsShopFreezeAmountLogDb->month = date('Y-m');
                $FWalletsShopFreezeAmountLogDb->tips = "总订单:{$order_count_sn},合计金额:{$user_shop_freeze_amount[$value]}";
                if (!$FWalletsShopFreezeAmountLogDb->save()) {
                    $this->dbMaster->rollback();
                    $this->fail(-1, '写入日志失败');
                }
                $shop_wallets->shop_freeze_amount = Common::bc($shop_wallets->shop_freeze_amount,$user_shop_freeze_amount[$value], "+", 2);
                if (!$shop_wallets->save()) {
                    $this->dbMaster->rollback();
                    $this->fail(-1, '写入冻结余额失败');
                }
            }

        }



        $BShopOrderCountDB = new BShopOrderCount();
        $BShopOrderCountDB->user_id = $this->user_info['id'];
        $BShopOrderCountDB->order_sn = $order_count_sn;
        $BShopOrderCountDB->address_id = $BShopOrderAddressDb->id;
        $BShopOrderCountDB->pay_order=$pay_order_sn;
        $BShopOrderCountDB->pay_type = $pay_type;
        $BShopOrderCountDB->pay_no = $pay_type == 3 ? "余额支付" : "";
        $BShopOrderCountDB->total_price = $order_all_mount;
        $BShopOrderCountDB->pay_time = $pay_type == 3 ?  date('Y-m-d H:i:s') : null;
        $BShopOrderCountDB->order_status = $pay_type == 3 ? 1 : 0;
        $BShopOrderCountDB->created_at = date('Y-m-d H:i:s');
        $BShopOrderCountDB->updated_at = date('Y-m-d H:i:s');
        if(!$BShopOrderCountDB->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'总订单写入出错');
        }


        $order_result['pay_type'] = $pay_type;
        switch ($pay_type){
            case 1: //支付宝
                $order_result['pay_info'] = $this->alipay->aliPay("商品购买",$order_all_mount,$order_count_sn);
                break;
            case 2: //微信
                $wx_pay = $this->xcx->pay_order("商品购买",$order_all_mount,$order_count_sn);
                if(!$wx_pay['code']){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'微信支付暂不可用');
                }
                $order_result['pay_info'] = $wx_pay['data'];
                break;
            case 3:
                //用户账户余额操作
                $FWalletsAmountLogDb = new FWalletsAmountLog();
                $FWalletsAmountLogDb->user_id = $this->user_info['id'];
                $FWalletsAmountLogDb->oil_num = $user_wallets->amount;
                $FWalletsAmountLogDb->this_num = Common::bc($user_wallets->amount,$order_all_mount,"-",2);
                $FWalletsAmountLogDb->num = $order_all_mount;
                $FWalletsAmountLogDb->status = 2;
                $FWalletsAmountLogDb->type = 3;
                $FWalletsAmountLogDb->remark = "余额购物";
                $FWalletsAmountLogDb->created_at = date('Y-m-d H:i:s');
                $FWalletsAmountLogDb->month = date('Y-m');
                $FWalletsAmountLogDb->tips = "总订单编号:{$order_count_sn},价格:{$order_all_mount}";
                if(!$FWalletsAmountLogDb->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'写入日志失败');
                }

                $user_wallets->amount = Common::bc($user_wallets->amount,$order_all_mount,"-",2);
                if(!$user_wallets->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'写入钱包出错');
                }
                $order_result['pay_type'] = $pay_type;
                $order_result['pay_info'] = (object)null;
                break;
            default:
                $this->fail(-1,'请选择支付方式');
        }
        $this->dbMaster->commit();
        $this->ok($order_result);

    }


    /**
     * 商品添加购物车
     */
    public function add_goods_cardAction(){
        $data['num']=1;
        $data['img'] = "http://qn.enshitc.com/1620462844093";
        $data['sku_id'] = 5;
        $data["goods_id"] = "5_20210813100646034190603";
        $data["goods_name"] = "这是测试商品";
        if(!isset($data['goods_id']) || empty($data['goods_id'])){
            $this->fail(-1,'商品id不能为空');
        }
        if(!isset($data['sku_id']) || empty($data['sku_id'])){
            $this->fail(-1,'商品sku不能为空');
        }
        if(!isset($data['num']) || empty($data['num'])){
            $this->fail(-1,'商品数量不能为空');
        }
        $data['user_id'] = $this->user_info['id'];
        $ShopOrderServices = new ShopOrderServices();
        $responseResult = $ShopOrderServices->addGoodsCard($data);
        if($responseResult['status']){
            $this->ok([]);
        }
        $this->fail(-1,$responseResult['msg']);
    }

    /**
     * 购物车列表
     */
    public function car_listAction(){
        $data['user_id'] = $this->user_info['id'];
        $ShopOrderServices = new ShopOrderServices();
        $responseResult = $ShopOrderServices->carList($data);
        $this->ok($responseResult);
    }


    /**
     * 删除购物车商品
     */
    public function car_delete_goodsAction(){
        if(!isset($this->params['ids']) || empty($this->params['ids'])){
            $this->fail(-1,'删除id不能为空');
        }
        $ShopOrderServices = new ShopOrderServices();
        $responseResult = $ShopOrderServices->carDeleteGoods($this->params);
        if(!$responseResult['status']){
            $this->fail(-1,$responseResult['msg']);
        }
        $this->ok([]);
    }



    /**
     * 我的订单列表
     */
    public function shop_orderAction(){
        if(!isset($this->params['page']) || empty($this->params['page'])){
            $this->params['page'] = 1;
        }
        if(!isset($this->params['limit']) || empty($this->params['limit'])){
            $this->params['limit']=10;
        }
        if(!isset($this->params['status'])){
            $this->params['status']="";
        }
        $BShopOrderDb = new BShopOrder();
        $get_list = $BShopOrderDb->get_list($this->params);
        $this->ok($get_list);
    }


    /**
     * 用户确认收货
     */
    public function confirm_goodsAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
//        if(!isset($this->params['msg_id']) || empty($this->params['msg_id'])){
//            $this->fail(-1,'短信模板不能为空');
//        }
//        if(!isset($this->params['msg_code']) || empty($this->params['msg_code'])){
//            $this->fail(-1,'验证码不能为空');
//        }

        $BShopOrderDb = new BShopOrder();
        $b_shop_order = $BShopOrderDb->findFirstByOrderSn($this->params['order_sn']);
        if(!$b_shop_order){
            $this->fail(-1,'没有找到记录行');
        }
        if($b_shop_order->user_id != $this->user_info['id']){
            $this->fail(-1,'该订单不是你的你不能操作该订单');
        }
        if(!in_array($b_shop_order->status,['2'])){
            $this->fail(-1,'你不能操作该订单');
        }
        $this->dbMaster->begin();

        $BShopUsersDb = new BShopUsers();
        $shop_user_id = $BShopUsersDb->find_shop_to_user_id($b_shop_order->shop_id);

        $FShopWalletsDb = new Wallets();
        $f_shop_wallets = $FShopWalletsDb->findFirstByUserId($shop_user_id);
        if(!$f_shop_wallets){
            $this->fail(-1,'没有找到店铺钱包');
        }

        $FWalletsShopFreezeAmountLogDb = new FWalletsShopFreezeAmountLog();
        $FWalletsShopFreezeAmountLogDb->user_id = $this->user_info['id'];
        $FWalletsShopFreezeAmountLogDb->shop_id = $shop_user_id;
        $FWalletsShopFreezeAmountLogDb->oil_num = $f_shop_wallets->shop_freeze_amount;
        $FWalletsShopFreezeAmountLogDb->this_num = Common::bc($f_shop_wallets->shop_freeze_amount,$b_shop_order->end_price,'-',2);
        $FWalletsShopFreezeAmountLogDb->num = $b_shop_order->end_price;
        $FWalletsShopFreezeAmountLogDb->status =2;
        $FWalletsShopFreezeAmountLogDb->type = 2;
        $FWalletsShopFreezeAmountLogDb->remark = "商品【{$b_shop_order->goods_name}】确认收货";
        $FWalletsShopFreezeAmountLogDb->created_at = date('Y-m-d H:i:s');
        $FWalletsShopFreezeAmountLogDb->month = date('Y-m');
        $FWalletsShopFreezeAmountLogDb->tips = "子订单:{$b_shop_order->order_sn},合计金额:{$b_shop_order->end_price}";
        if(!$FWalletsShopFreezeAmountLogDb->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'添加店铺冻结日志报错');
        }


        $FWalletsShopAmountLogDb = new FWalletsShopAmountLog();
        $FWalletsShopAmountLogDb->shop_id = $b_shop_order->shop_id;
        $FWalletsShopAmountLogDb->user_id = $this->user_info['id'];
        $FWalletsShopAmountLogDb->oil_num = $f_shop_wallets->shop_amount;
        $FWalletsShopAmountLogDb->this_num = Common::bc($f_shop_wallets->shop_amount,$b_shop_order->end_price,'+',2);
        $FWalletsShopAmountLogDb->num = $b_shop_order->end_price;
        $FWalletsShopAmountLogDb->status =1;
        $FWalletsShopAmountLogDb->type = 1;
        $FWalletsShopAmountLogDb->remark = "商品【{$b_shop_order->goods_name}】确认收货";
        $FWalletsShopAmountLogDb->created_at = date('Y-m-d H:i:s');
        $FWalletsShopAmountLogDb->month = date('Y-m');
        $FWalletsShopAmountLogDb->tips = "子订单:{$b_shop_order->order_sn},合计金额:{$b_shop_order->end_price}";
        if(!$FWalletsShopAmountLogDb->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'添加店铺余额日志报错');
        }

        $f_shop_wallets->shop_amount = Common::bc($f_shop_wallets->shop_amount,$b_shop_order->end_price,'+',2);
        $f_shop_wallets->shop_freeze_amount = Common::bc($f_shop_wallets->shop_freeze_amount,$b_shop_order->end_price,'-',2);
        if(!$f_shop_wallets->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'添加店铺余额报错');
        }

        $b_shop_order->status=4;
        $b_shop_order->updated_at = date('Y-m-d H:i:s');
        $b_shop_order->settle_type = 1;
        if(!$b_shop_order->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'店铺订单修改报错');
        }

        $BShopOrderCountDb = new BShopOrderCount();
        $b_shop_order_count = $BShopOrderCountDb->findFirstByOrderSn($b_shop_order->order_count_sn);
        $b_shop_order_count->order_status = 4;
        $b_shop_order_count->updated_at = date('Y-m-d H:i:s');
        if(!$b_shop_order_count){
            $this->dbMaster->rollback();
            $this->fail(-1,'店铺总订单修改报错');
        }
        $this->dbMaster->commit();
        $this->ok([]);
    }

    public function reasion_listAction(){
        $BShopRefundReasionDb = new BShopRefundReasion();
        $shop_refund_reasion = $BShopRefundReasionDb->find()->toarray();
        $get_list=[];
        foreach($shop_refund_reasion as $key=>$value){
            $get_list[$key] = $value['reasion'];
        }
        $this->ok($get_list);
    }


    /**
     * 我要退款 退货
     */
    public function refund_orderAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
        if(!isset($this->params['type']) || empty($this->params['type'])){
            $this->fail(-1,'类型不能为空');
        }else{
            if(!in_array($this->params['type'],[1,2])){
                $this->fail(-1,'类型错误');
            }
        }
        if(!isset($this->params['goods_type']) || empty($this->params['goods_type'])){
            $this->fail(-1,'请选择货物状态');
        }
        if(!isset($this->params['reasion']) || empty($this->params['reasion'])){
            $this->fail(-1,'请选择原因');
        }
        if(!isset($this->params['remark']) || empty($this->params['remark'])){
            $this->params['remark']='';
        }
        $this->params['img']='';
        if(isset($this->params['img1']) && !empty($this->params['img1'])){
            if(!strpos($this->params['img1'],'img_zhanwei.jpg') !== false){
                $this->params['img']=$this->params['img1'];
            }
        }
        if(isset($this->params['img2']) && !empty($this->params['img2'])){
            if(!strpos($this->params['img2'],'img_zhanwei.jpg') !== false){
                $this->params['img']=$this->params['img'] ? $this->params['img'].','. $this->params['img2'] : '';
            }
        }
        if(isset($this->params['img3']) && !empty($this->params['img3'])){
            if(!strpos($this->params['img3'],'img_zhanwei.jpg') !== false){
                $this->params['img']=$this->params['img'] ? $this->params['img'].','. $this->params['img3'] : '';
            }
        }

        $this->dbMaster->begin();
        $BShopOrderDb = new BShopOrder();
        $b_shop_order = $BShopOrderDb->findFirstByOrderSn($this->params['order_sn']);
        if(!$b_shop_order){
            $this->fail(-1,'没有找到记录行');
        }
        if($b_shop_order->user_id != $this->user_info['id']){
            $this->fail(-1,'你不能操作该订单!');
        }
        $BShopOrderRefundDb = new BShopOrderRefund();
        $b_shop_order_refund = $BShopOrderRefundDb->findFirstByOrderSn($b_shop_order->order_sn);
        if($b_shop_order_refund && $b_shop_order_refund->shop_is_agree == 0){
            $this->fail(-1,'您的申请已经提交，等待商家处理');
        }
        if(!$b_shop_order_refund){
            $b_shop_order_refund = new BShopOrderRefund();
            $b_shop_order_refund->order_sn = $b_shop_order->order_sn;
        }
        $b_shop_order_refund->type = $this->params['type'];
        $b_shop_order_refund->goods_type = $this->params['goods_type'];
        $b_shop_order_refund->reasion_id = 0;
        $b_shop_order_refund->reasion =$this->params['reasion'];
        $b_shop_order_refund->remark = $this->params['remark'];
        $b_shop_order_refund->img = $this->params['img'];
        $b_shop_order_refund->created_at = date('Y-m-d H:i:s');
        $b_shop_order_refund->user_id = $this->user_info['id'];
        $b_shop_order_refund->shop_is_agree = 0;
        $tips=isset($b_shop_order_refund->tips) ? "{$b_shop_order_refund->tips}|用户发起了":"用户发起了";
        $b_shop_order_refund->tips = $this->params['type'] == 1 ? "{$tips}退货申请" : "{$tips}退款申请";
        if(!$b_shop_order_refund->save()){
            $this->fail(-1,'操作失败');
        }

        $BShopOrderCountDb = new BShopOrderCount();
        $b_shop_order_count = $BShopOrderCountDb->findFirstByOrderSn($b_shop_order->order_count_sn);
        if(!$b_shop_order_count){
            $this->fail(-1,'没有找到订单');
        }
        $b_shop_order_count->order_status = $this->params['type']==1 ? 5 : -2;
        $b_shop_order_count->updated_at = date('Y-m-d H:i:s');
        if(!$b_shop_order_count->save()){
            $this->fail(-1,'操作失败');
        }

        $b_shop_order->status = $this->params['type']==1 ? 5 : -2;
        $b_shop_order->refund_id = $b_shop_order_refund->id;
        $tips="{$b_shop_order->tips}|用户发起了";
        $b_shop_order->tips =  $this->params['type'] == 1 ? "{$tips}退货申请" : "{$tips}退款申请";
        if(!$b_shop_order->save()){
            $this->fail(-1,'操作失败');
        }
        $this->dbMaster->commit();
        $this->ok([]);
    }



    public function orderdetailAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
        $BShopOrderDb = new BShopOrder();
        $get_list = $BShopOrderDb->get_order_detail($this->params['order_sn']);
        $BshopGoodsCommentDb = new BShopGoodsComment();
        $is_comment = $BshopGoodsCommentDb->findFirst("user_id={$this->user_info['id']} AND id={$get_list['id']}");
        $get_list['is_comment'] = $is_comment ? true :false;
        $BShopOrderRefundDb = new BShopOrderRefund();
        $is_comment = $BShopOrderRefundDb->findFirst("user_id={$this->user_info['id']} AND order_sn='{$this->params['order_sn']}'");
        $get_list['refund']['is_refund'] = $is_comment ? true :false;
        $get_list['refund']['refund_info'] = $is_comment;
        $this->ok($get_list);
    }


    /**
     * 快递单号查询
     */
    public function express_infoAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
        $BShopOrderDb = new BShopOrder();
        $b_shop_order = $BShopOrderDb->findFirstByOrderSn($this->params['order_sn']);
        if(!$b_shop_order){
            $this->fail(-1,'没有找到记录行');
        }
        //$BShopExpressDb = new
        $list = Common::express_list("777047814861045");
        $list->ico = "http://www.kuaidi.com".$list->ico;
        $this->ok($list);
    }



    /**
     * 支付待支付的订单
     */
    public function nopay_ordersnAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
        if(!isset($this->params['type']) || empty($this->params['type'])){
            $this->fail(-1,'支付方式不能为空');
        }else{
            if(!in_array($this->params['type'],[1,2,3])){
                $this->fail(-1,'类型错误');
            }
        }
        $BShopOrderDb = new BShopOrder();
        $b_shop_order = $BShopOrderDb->findFirstByOrderSn($this->params['order_sn']);
        if(!$b_shop_order){
            $this->fail(-1,'没有找到订单记录');
        }
        if($b_shop_order->status != 0){
            $this->fail(-1,'该订单不可操作，请刷新列表');
        }


        switch ($this->params['type']){
            case 1: //支付宝
                $order_result['pay_info'] = $this->alipay->aliPay("商品购买",$b_shop_order->end_price,$b_shop_order->order_sn);
                break;
            case 2: //微信
                $wx_pay = $this->xcx->pay_order("商品购买",$b_shop_order->end_price,$b_shop_order->order_sn);
                if(!$wx_pay['code']){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'微信支付暂不可用');
                }
                $order_result['pay_info'] = $wx_pay['data'];
                break;
            case 3:
                $b_shop_order->status = 1;
                $b_shop_order->updated_at = date('Y-m-d H:i:s');
                $b_shop_order->pay_type = 3;
                $b_shop_order->pay_time = date('Y-m-d H:i:s');
                $b_shop_order->tips .= "|用户10分钟之内重新付款";
                if(!$b_shop_order->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'更改订单状态失败');
                }


                $FWalletsDb = new Wallets();
                $user_wallets = $FWalletsDb->findFirstByUserId($this->user_info['id']);
                if(!$user_wallets){
                    $this->fail(-1,'没有找到用户钱包');
                }
                if($user_wallets->amount < $b_shop_order->end_price){
                    $this->fail(-1,'钱包余额不足');
                }
                //用户账户余额操作
                $FWalletsAmountLogDb = new FWalletsAmountLog();
                $FWalletsAmountLogDb->user_id = $this->user_info['id'];
                $FWalletsAmountLogDb->oil_num = $user_wallets->amount;
                $FWalletsAmountLogDb->this_num = Common::bc($user_wallets->amount,$b_shop_order->end_price,"-",2);
                $FWalletsAmountLogDb->num = $b_shop_order->end_price;
                $FWalletsAmountLogDb->status = 2;
                $FWalletsAmountLogDb->type = 3;
                $FWalletsAmountLogDb->remark = "余额购物";
                $FWalletsAmountLogDb->created_at = date('Y-m-d H:i:s');
                $FWalletsAmountLogDb->month = date('Y-m');
                $FWalletsAmountLogDb->tips = "总订单编号:{$b_shop_order->order_count_sn},价格:{$b_shop_order->end_price}";
                if(!$FWalletsAmountLogDb->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'写入日志失败');
                }

                $user_wallets->amount = Common::bc($user_wallets->amount,$b_shop_order->end_price,"-",2);
                if(!$user_wallets->save()){
                    $this->dbMaster->rollback();
                    $this->fail(-1,'写入钱包出错');
                }
                $order_result['pay_type'] = $this->params['type'];
                $order_result['pay_info'] = (object)null;
                break;
            default:
                $this->fail(-1,'请选择支付方式');
        }

        $this->ok($order_result);

    }


    /**
     * 评论商品
     */
    public function comment_goodsAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
        $BShopOrderDb = new BShopOrder();
        $b_shop_order = $BShopOrderDb->findFirstByOrderSn($this->params['order_sn']);
        if(!$b_shop_order){
            $this->fail(-1,'没有找到订单号');
        }

        if(!isset($this->params['star']) || empty($this->params['star'])){
            $this->fail(-1,'请为我们的满意度打分');
        }

        if(!isset($this->params['content']) || empty($this->params['content'])){
            $this->fail(-1,'请为我们的服务做出评价');
        }
        if(!isset($this->params['descript_star']) || empty($this->params['descript_star'])){
            $this->fail(-1,'请为我们描述相符打分');
        }
        if(!isset($this->params['express_star']) || empty($this->params['express_star'])){
            $this->fail(-1,'请为物流服务打分');
        }
        if(!isset($this->params['service_star']) || empty($this->params['service_star'])){
            $this->fail(-1,'请为服务态度打分');
        }
        $BShopGoodsCommentDb = new BShopGoodsComment();
        $exit_comment = $BShopGoodsCommentDb->exit_user_comment($this->user_info['id'],$this->params['order_sn']);
        if($exit_comment){
            $this->fail(-1,'您已经评论过该商品');
        }
        $this->params['img']='';
        if(isset($this->params['img1']) && !empty($this->params['img1'])){
            if(!strpos($this->params['img1'],'img_zhanwei.jpg') !== false){
                $this->params['img']=$this->params['img1'];
            }
        }
        if(isset($this->params['img2']) && !empty($this->params['img2'])){
            if(!strpos($this->params['img2'],'img_zhanwei.jpg') !== false){
                $this->params['img']=$this->params['img'] ? $this->params['img'].','. $this->params['img2'] : '';
            }
        }
        if(isset($this->params['img3']) && !empty($this->params['img3'])){
            if(!strpos($this->params['img3'],'img_zhanwei.jpg') !== false){
                $this->params['img']=$this->params['img'] ? $this->params['img'].','. $this->params['img3'] : '';
            }
        }

        $this->dbMaster->begin();
        $BShopGoodsCommentDb = new BShopGoodsComment();
        $BShopGoodsCommentDb->user_id = $this->user_info['id'];
        $BShopGoodsCommentDb->shop_id = $b_shop_order->shop_id;
        $BShopGoodsCommentDb->content = $this->params['content'];
        $BShopGoodsCommentDb->created_at = date('Y-m-d H:i:s');
        $BShopGoodsCommentDb->star = $this->params['star'];
        $BShopGoodsCommentDb->goods_id = $b_shop_order->goods_id;
        $BShopGoodsCommentDb->descript_star = $this->params['descript_star'];
        $BShopGoodsCommentDb->express_star = $this->params['express_star'];
        $BShopGoodsCommentDb->service_star = $this->params['service_star'];
        $BShopGoodsCommentDb->order_sn = $b_shop_order->order_sn;
        $BShopGoodsCommentDb->o_id = $b_shop_order->id;
        $BShopGoodsCommentDb->img = $this->params['img'];
        if(!$BShopGoodsCommentDb->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'评论失败');
        }

        $b_shop_order->status = 7;
        $b_shop_order->updated_at = date('Y-m-d H:i:s');
        if(!$b_shop_order->save()){
            $this->dbMaster->rollback();
            $this->fail(-1,'评论失败');
        }

        $BShopGoodsDb = new BShopGoods();
        $b_shop_goods = $BShopGoodsDb->findFirstById($b_shop_order->goods_id);
        if(!$b_shop_goods){
            $this->dbMaster->commit();
            $this->ok([]);
        }
        $b_shop_goods->goods_commit = $b_shop_goods->goods_commit + 1;
        $b_shop_goods->good_commit_rate = $BShopGoodsCommentDb->goods_comment_rate($b_shop_order->goods_id);
        if($b_shop_goods->save()){
            $this->dbMaster->commit();
            $this->ok([]);
        }
        $this->dbMaster->commit();
        $this->ok([]);
    }



    /**
     * 提醒发货
     */
    public function remind_goodsAction(){
        if(!isset($this->params['order_sn']) || empty($this->params['order_sn'])){
            $this->fail(-1,'订单号不能为空');
        }
        $BShopOrderDb = new BShopOrder();
        $b_shop_order = $BShopOrderDb->findFirstByOrderSn($this->params['order_sn']);
        if(!$b_shop_order){
            $this->fail(-1,'没有找到订单号');
        }
        if($b_shop_order->user_id != $this->user_info['id']){
            $this->fail(-1,'该订单不可操作');
        }
        if($b_shop_order->status != 1){
            $this->fail(-1,'该订单状态不可操作');
        }

        $this->params['shop_id'] = $b_shop_order->shop_id;
        $BShopMessageSystemDb = new BShopMessageSysmess();
        $find_message_system = $BShopMessageSystemDb->find_one_system1($this->params);
        if($find_message_system){
            $this->fail(-1,'您今天已经提醒卖家发货了');
        }

        $BShopAddressDb = new BShopOrderAddress();
        $b_shop_address = $BShopAddressDb->findFirstById($b_shop_order->address_id);
        $message = "<p>用户发来发货提醒<br/>订单号：{$this->params['order_sn']}<br/>姓名：{$b_shop_address->name}<br/>手机号：{$b_shop_address->phone}<br/>详细地址：{$b_shop_address->address}</p>";

        $BShopMessageSystemDb->sys_id = "system2";
        $BShopMessageSystemDb->message = $message;
        $BShopMessageSystemDb->created_at = date('Y-m-d H:i:s');
        $BShopMessageSystemDb->updated_at = date('Y-m-d H:i:s');
        $BShopMessageSystemDb->type = "text";
        $BShopMessageSystemDb->msg_type = "user";
        $BShopMessageSystemDb->extends = $this->params['order_sn'];
        $BShopMessageSystemDb->shop_id = $b_shop_order->shop_id;
        $BShopMessageSystemDb->send_message_id = $this->user_info['id'];
        $BShopMessageSystemDb->sys_type = 1;
        if(!$BShopMessageSystemDb->save()){
            $this->fail(-1,'提醒失败');
        }
        $this->ok([]);
    }

}
